<?php
class adjAction extends HomeAction {

	protected function _initialize() {
        $freeAuth = array('login', 'liveTest',"share","quche"); //在微信端不用置入openid的方法

        if ( strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') == false && ACTION_NAME!="liveTest") {
            $this->assign("Server",'other');//非微信端
            $_SESSION['Server'] = 'other';
        }else if(!in_array(ACTION_NAME, $freeAuth)){
            $this->assign("Server",'wx');//微信端
            $_SESSION['Server'] = 'wx';
            if($_REQUEST['open_id']){
                $_SESSION['open_id'] = $_REQUEST['open_id'];
            }
            if(empty($_SESSION['open_id'])) {
                vendor('WxPay/WxPayPubHelper');
                $jsApi = new JsApi_pub();
                if (!isset($_GET['code'])){

                    $url=C('WEB_URL').'adj/';
                    $url = $jsApi->createOauthUrlForCode($url);
                    Header("Location: $url");exit("数据初始化中..");
                }else{
                    $code = $_GET['code'];
                    $jsApi->setCode($code);
                    $_SESSION['open_id'] = $jsApi->getOpenId();
                }
                unset($_SESSION['user']);
            }
            if(empty($_SESSION['user']) && !empty($_SESSION['open_id'])){
                $Info = M('user')->field('user_id,open_id,username,nickname,realname,address')->where("open_id='".$_SESSION['open_id']."'")->find();
                if($Info){                                  //初始化验证用户
                    $U = M('user_auto');
                    $model = $U->join('hx_auto_model m on hx_user_auto.model_id=m.model_id')->where("user_id=".$Info['user_id']." and hx_user_auto.default=1")->find();

                    $Info['model'] = $model;
                    $_SESSION['order']['model_id'] = $model['model_id'];
                    $_SESSION['order']['realname']=$Info["realname"];
                    $_SESSION['order']['phone']=$Info["username"];
                    $_SESSION['user'] = $Info;              //session记录数据
                    $_SESSION['location']=$Info['city'];
                }
            }
        }
    }

	public function index(){

		$O=M('order');
		$map['status']=array('BETWEEN',"6,70");
		$map['user_id']=$_SESSION['user']['user_id'];
		$map['address_back']=array("neq","");
		$order=$O->where($map)->find();

		//服务项目
        $mapS['s_id']=array("in","1,3,4,5");
        $mapS['status']=1;
        $service=M("service")->where($mapS)->select();
        $this->assign("service",$service);

		if($order){
			if($order['sign_time']!=""&&$order['status']<50){
				$orderStatus=8;
			}elseif($order['status']==50&&$order['end_time']==null){
				$orderStatus=50;
			}elseif($order['status']==50&&$order['pay_type']==0){
				$orderStatus=55;
			}elseif($order['status']==60&&$order['pay_type']!=0){
				$orderStatus=60;
			}else{
				$orderStatus=$order['status'];
			}

			$this->assign("orderStatus",$orderStatus);
			$this->assign("order",$order);
		}
		$this->display("index");
	}

	//代驾订单详情
	public function djInfo(){
		$O=M('order');
		$map['status']=array('BETWEEN',"6,70");
		$map['user_id']=$_SESSION['user']['user_id'];
		$map['address_back']=array("neq","");
		$order=$O->where($map)->find();
		if($order!=null){
			if($order['sign_time']!=""&&$order['status']<50){
				//已签到，还没开始保养
				$this->step5($order);
			}elseif($order['status']==6){
				//已存在订单，指派司机中
				$this->step2($order);
			}elseif($order['status']==7){
				//等待代驾状态
				$this->step3($order);
			}elseif($order['status']==8){
				//接车代驾中
				$this->step4($order);
			}elseif($order['status']==50&&$order['end_time']==null){
				//正在保养
				$this->step6($order);
			}elseif($order['status']==60&&$order['pay_type']==0){
				//保养结束，等待付款
				$this->step7($order);
			}elseif($order['status']==60&&$order['pay_type']!=0){
				//已支付,
				$this->step8($order);
			}elseif($order['status']==65){
				//司机正在取车路上
				//$this->step10($order);
				$this->step8($order);
			}elseif($order['status']==67){
				//司机正在还车路上
				$this->step11($order);
			}elseif($order['status']==70){
				$this->step12($order);
			}
		}

	}


	public function getOrderStatus(){

		$O=M('order');
		$map['order_id']=$_POST['orderId'];
		$map['user_id']=$_SESSION['user']['user_id'];
		$order=$O->where($map)->find();
		if(!$order){
			$this->ajaxReturn(false,"订单不存在",0);
		}

		$limitStart=$order['status']<50?0:1;	//小于50则处理保养前
		$orderAdj=M("order_adj");
		$info=$orderAdj->where("order_id=".$_POST['orderId'])->limit("$limitStart,1")->select();
		$info=$info[0];
		if($info){
			$_POST['orderId']=$info['adj_id'];	//重置ID为爱代驾，用于获取订单详情
			$adjOrderInfo=$this->getOrderInfo();

			if($adjOrderInfo['Status']>=40){
				//爱代驾取消订单引起取消去保养订单
				$map['order_id']=$_POST['orderId'];
				$map['status']=array("lt",8);
				$O=M("order");
				$res=$O->where($map)->setField("status",100);
				if($res){
					log::write("取消订单".$map['order_id']."结果：".$data);
				}
			}else if($info['type']==1&&$adjOrderInfo['Status']==11&&$order['status']==6){
				//接车司机已接单
				$statusNow=7;
			}else if($info['type']==1&&$adjOrderInfo['Status']==21){
				//接车已开始
				$statusNow=8;
			}else if($info['type']==2&&$adjOrderInfo['Status']==11&&$order['status']==60&&$order['pay_type']!=0){
				//送车司机已接单
				$statusNow=65;
			}else if($info['type']==2&&$adjOrderInfo['Status']==21){
				//正在送车
				$statusNow=67;
			}else if($info['type']==2&&($adjOrderInfo['Status']==22||$adjOrderInfo['Status']==30)){
				$statusNow=70;
			}


			//判断是否需要更新订单状态
			if(!empty($statusNow)&&$order['status']!=70&&$order['status']!=71&&$order['status']!=$statusNow){

				$res=$O->where($map)->setField("status",$statusNow);
				if($res){
					$order['status']=$statusNow;
					
					//微信推送信息
					$_SESSION['open_id']="oizF2uHtGlafea7V6TJw9l2JCYo8";	//测试用
					if($_SESSION['open_id']){
						$arr=array(
							7=>"司机大叔已接到接车命令，正火速赶来！",
							8=>"司机大叔已经开着您的爱车前往去保养啦！",
							67=>"别急，司机大叔已经在回归路上，争取尽快让您见到爱车！",
							70=>"任务完成，司机大叔屁颠屁颠回去啦~感谢您对去保养的支持！"
						);
						$url = 'http://wechat.99qby.com/app/index.php?i=4&c=entry&do=index2&m=we7_demo&open_id='.$_SESSION['open_id'].'&type=5&content='.$arr[$statusNow];

						$this->https_request($url);
					}
				}
			}
		}

		if($order['sign_time']!=""&&$order['status']<50){
			$orderStatus=9;
		}else if($order['status']==50&&$order['end_time']==null){
			$orderStatus=50;
		}else if($order['status']==50&&$order['pay_type']==0){
			$orderStatus=55;
		}else if($order['status']==60&&$order['pay_type']!=0){
			$orderStatus=60;
		}else{
			$orderStatus=$order['status'];
		}
		$this->ajaxReturn($orderStatus,"成功获取最新状态",1);
	}

	public function step2($order){
		$this->assign("order",$order);
		$this->display("step2");
		exit;
	}

	public function step3($order){
		$map['type']=1;
		$map['user_id']=$order['order_id'];
		$adjOrder=M("order_adj")->where($map)->find();

		$this->assign("adjOrder",$adjOrder);
		$this->assign("order",$order);
		$this->display("step3");
		exit;
	}

	public function step4($order){
		$map['type']=1;
		$map['user_id']=$order['order_id'];
		$adjOrder=M("order_adj")->where($map)->find();
		$company=M("company")->field("wx_name,wx_address")->where("wx_id=".$order['wx_id'])->find();
		$this->assign("company",$company);
		$this->assign("adjOrder",$adjOrder);
		$this->display("step4");
		exit;
	}
	public function step5($order){
		$map['type']=1;
		$map['user_id']=$order['order_id'];
		$adjOrder=M("order_adj")->where($map)->find();
		$company=M("company")->field("wx_name,wx_address")->where("wx_id=".$order['wx_id'])->find();
		$this->assign("company",$company);
		
		$this->assign("img",json_decode($order['sign_img'],true));
		$this->display("step5");
		exit;
	}
	public function step6($order){
		$this->assign("order",$order);
		$this->assign("img",json_decode($order['sign_img'],true));
		$this->display("step6");
		exit;
	}
	public function step7($order){
		$map['order_id']=$order['order_id'];
		$orderInfo=M("order_info")->where($map)->limit(2)->select();
		$this->assign("info",$orderInfo);
		$this->assign("order",$order);
		$this->display("step7");
		exit;
	}

	public function step8($order){
		$this->display("step8");
		exit;
	}

	public function step9($order){
		$this->display("step9");
		exit;
	}

	public function step10($order){
		$map['type']=2;
		$map['user_id']=$order['order_id'];
		$adjOrder=M("order_adj")->where($map)->find();
		$this->assign("adjOrder",$adjOrder);
		$this->assign("order",$order);
		$this->display("step10");
		exit;
	}

	public function step11($order){
		$map['type']=2;
		$map['user_id']=$order['order_id'];
		$adjOrder=M("order_adj")->where($map)->find();
		$this->assign("adjOrder",$adjOrder);
		$this->assign("order",$order);
		$this->display("step11");
		exit;
	}

	public function step12($order){
		$this->assign("order",$order);
		$this->display("step12");
		exit;
	}

	//关闭订单
	public function replayOrder(){
		$this->display();
	}

	//用户取消去保养定单
	public function closeOrderQBY(){
		$O=M('order');
		$data['status']=100;
		$data['order_id']=$_POST["orderId"];
		$res=$O->save($data);

		$order=$O->where($data)->find();
		$content="【取消上门取车】".$order['order_num']."号订单的车主取消了上门取车的请求，请及时处理";
        //给客服发信息
        $this->postSms(C("kefuPhone"),$content);

		if($res){
			$this->ajaxReturn($data,"取消订单成功",1);
		}else{
			$this->ajaxReturn(null,"取消订单失败",0);
		}
	}


	//订单结束(流程走完)
	public function orderOver(){
		$O=M('order');
		$data['status']=71;
		$data['order_id']=$_POST["orderId"];
		$res=$O->save($data);

		if($res){
			$this->ajaxReturn(true,"订单完成成功",1);
		}else{
			$this->ajaxReturn(null,"订单完成失败",0);
		}
	}

	//获取附近司机列表
	public function getSJ(){
		$sign=C("adjKey");	//合作商KEY

		$lat=$_POST['lat'];
		$lng=$_POST['lng'];
		$imei="imei";
		$md5=md5($lat.$lng."aidaijia");
		$url="http://p.aidaijia.com/pservice.aspx";
		$string="1201|".$lat."|".$lng."|".$sign."|".$imei."|".$md5;
		$data=$this->curls($url,$string);

		if(substr($data,0,3)=="EX|"){
			log::write("获取附近司机列表出错：".$data);
			$this->ajaxReturn(false,"网络忙，请重试",0);
		}else{
			$data=json_decode($data,true);
			if(empty($_POST['phone'])){
				$this->ajaxReturn($data,"获取成功",1);
			}else{
				//服务端调用，获取最近司机创建订单
				return $data;
			}
		}
	}

	//获取司机评价列表
	public function getSJComment(){

		$sign=C("adjKey");	//合作商KEY
		$ucode=$_POST['ucode'];

		$imei="imei";
		$md5=md5($ucode."aidaijia");
		$url="http://p.aidaijia.com/pservice.aspx";
		$string="1207|".$sign."|".$ucode."|".$imei."|".$md5;
		$data=$this->curls($url,$string);

		if(substr($data,0,3)=="EX|"){
			log::write("获取司机评价出错".$data);
			$this->ajaxReturn(false,"网络忙，请重试",0);
		}else{
			$data=json_decode($data,true);
			$this->ajaxReturn($data,"获取成功",1);
		}
	}

	//创建去保养订单
	public function createOrder(){

		//查看是否已注册
		$U = M("user");
		$data['username'] = $_POST['phone'];
		$userInfo=$U->where($data)->field("user_id,open_id,username,nickname,realname,address")->find();
		$ua_id = 0;
	
		$_SESSION['user']=$userInfo;
		if (!$userInfo||empty($_SESSION['user'])) {
			//注册用户并插入数据
			$userInfo['create_time'] = time();
			$userInfo['tel'] = $_POST['phone'];
			$userInfo['nickname'] = $_POST['phone'];
			$userInfo['username'] = $_POST['phone'];
			$userInfo['password'] = md5("123456");
			$userInfo['realname']=$_POST['realname'];
			$userInfo['address']=$_POST['address'];
			if($_SESSION['open_id']){
				$userInfo['open_id'] = $_SESSION['open_id'];
			}
			$user_id = $U->add($userInfo); //注册用户
			if($user_id){
				$userInfo['user_id'] = $user_id;
				$_SESSION['user'] = $userInfo;              //session记录数据
			}
		}else{
			if(!empty($_SESSION['open_id'])){
				//绑定微信OPENID
				$dataUserInfo['open_id']=$_SESSION['open_id'];
			}
			$dataUserInfo['realname']=$_SESSION['order']['realname'];
			$res = $U->where("user_id=".$userInfo['user_id'])->save($dataUserInfo);

			$_SESSION['user'] = $userInfo;              //session记录数据
		}
	
		$dataOrder['order_num']=time().rand(100, 999);
		$dataOrder['user_id']=$_SESSION['user']['user_id'];
		$dataOrder['wx_id']=$_POST['wx_id'];

		$dataOrder['ua_id']=$ua_id;
		$dataOrder['create_time']=time();

		$dataOrder['type']=$_POST['serverType'];
		$dataOrder['server']=$_POST['serverList'];

		$dataOrder['address_back']=$_POST['addressBack'];
		$dataOrder['address_start']=$_POST['address'];
		$dataOrder['uo_type']=3;
		$dataOrder['status']=6;	//等待接车代驾
		$dataOrder['source']=$_SESSION['order']['source'];

		$dataOrder['yy_date']=strtotime(date('Y-m-d'));
		$dataOrder['yy_time']=3;

		$mapS['s_id']=array('in',$_POST['serverList']);
		$serverList=M("service")->where($mapS)->select();

		foreach($serverList as $key=>$value){
			$dataOrder['order_name'].=$dataOrder['order_name']==""?$value['name']:"、".$value['name'];
			
			//计算服务费
			if($value["s_id"]==1||$value["s_id"]==2){
				$dataOrder['service_price']=$value['price'];
			}
		}
		
		$partOrder=M('order');

		$order_id=$partOrder->add($dataOrder);
		$_SESSION['order']['order_id']=$order_id;
	
		if($order_id){
			$content="【".$_POST['name']."】需要上门取车服务，联系电话：".$_POST['phone']."；取车地址：".str_replace(' ','',$_POST['address']);

        	//给客服发信息
        	$this->postSms(C("kefuPhone"),$content); //13611679005
			$this->ajaxReturn($order_id,"创建订单成功",1);

		}else{
			log::write("用户".$_SESSION['user']['username']."下单失败");
		}
	}

	//创建订单，获取订单号 2.10接口
	public function createOrderNow(){
		$orderIdQBY=$this->createOrder();	//创建订单

		$sign=C("adjKey");	//合作商KEY
		$orderId=$_POST['orderId'];

		$name=$_POST['name'];
		$phone=$_POST['phone'];
		$address=trim($_POST['address']);
		$lat=$_POST['lat'];
		$lng=$_POST['lng'];
		$imei="imei";
		$md5=md5($phone."aidaijia");

		$shiji=$this->getSJ();	//获取周围司机

		for($i=0;$i<count($shiji);$i++){
			//获取最近空闲司机
			if($shiji[$i]['state']=="空闲中"){
				$ucode=$shiji[$i]["ucode"];
				break;
			}
		}

		if(empty($ucode)){
			$this->ajaxReturn(false,"很抱歉，周围司机都在服务中",0);
		}

		$url="http://p.aidaijia.com/pservice.aspx";
		$string="1212|".$name."|".$phone."|".$address."|".$ucode."|".$lat."|".$lng."|8|".$sign."|imei|".$md5."|99qby";

		$adj_id=$this->curls($url,$string);

		if(substr($adj_id,0,3)=="EX|"){
			log::write("即时创建订单失败".$adj_id);
			$this->ajaxReturn(false,"网络忙，请重试",0);
		}else{
			$data['order_id']=$orderIdQBY;
			$data['adj_id']=$adj_id;
			$data['create_time']=time();
			$data['type']=1;
			$data['status']=0;
			$res=M("order_adj")->add($data);
			if($res){
				$this->ajaxReturn($adj_id,"创建订单成功",1);
			}else{
				log::write("创建爱代驾订单失败，ID:".$adj_id);
				$res=M('order')->where('dj_id='.$orderIdQBY)->delete();
				$this->ajaxReturn(false,"网络忙，请重试",0);
			}
		}
	}

	//获取爱代驾订单详情，接口号：2.11 	type:1取车，2：还车
	public function getOrderInfo(){

		$sign=C("adjKey");	//合作商KEY
		$orderId=$_POST['orderId'];

		$imei="imei";
		$md5=md5($orderId."aidaijia");
		$url="http://p.aidaijia.com/pservice.aspx";
		$string="1213|".$orderId."|".$sign."|".$imei."|".$md5;

		$data=$this->curls($url,$string);
		log::write("_____".$url.$string);
		log::write("获取订单详情".$orderId."结果：".$data);

		if(substr($data,0,3)=="EX|"){
			//$this->ajaxReturn(false,"网络忙，请重试",0);
		}else{
			$data=json_decode($data,true);
			$data=$data[0];
			if($data['Status']>=22){
				$this->updateOrderInfo($data);
			}
			return $data;
			$this->ajaxReturn($data,"获取订单成功",1);
		}
	}

	//更新订单数据
	public function updateOrderInfo($data){
		if($data['Status']>=40){
			//爱代驾取消订单引起取消去保养订单

			$map['order_id']=M('order_adj')->where("adj_id='".$data['OrderId']."'")->getField("order_id");
			$map['status']=array("lt",8);
			$O=M("order");
			$res=$O->where($map)->setField("status",100);
			log::write("_____________".$O->getLastSql());
			if($res){
				log::write("取消订单".$map['order_id']."结果：".$data);
			}
		}elseif($data['Status']>=22){
			//代驾结束，更新数据
			$dataAdj["start_address"]=$data["Address"];
			$dataAdj["ucode"]=$data["Ucode"];
			$dataAdj["wait_time"]=$data["WaitTime"];
			$dataAdj["wait_money"]=$data["WaitMoney"];
			$dataAdj["start_lat"]=$data["DriverLat"];
			$dataAdj["start_lng"]=$data["DriverLng"];
			$dataAdj["mileage"]=$data["Mileage"];
			$dataAdj["mileage_money"]=$data["MileageMoney"];
			$dataAdj["total_money"]=$data["AllMoney"];
			$dataAdj["appoint_time"]=$data["AppointTime"];
			$OA=M("order_adj");
			$res=$OA->where("adj_id='".$data['OrderId']."'")->save($dataAdj);

		}
	}


	//取消爱代驾订单
	public function closeOrder(){
		$sign=C("adjKey");	//合作商KEY
		$orderId=$_POST['orderId'];
		//$orderId="HMMQWNSS2Z4U";
		$imei="imei";
		$md5=md5($orderId."aidaijia");
		$url="http://p.aidaijia.com/pservice.aspx";
		$string="1209|".$orderId."|".$sign."|".$md5;
		$data=$this->curls($url,$string);
		log::write("取消爱代驾订单".$orderId."结果：".$data);

		if(substr($data,0,3)=="EX|"||$data==0){
			$this->ajaxReturn(false,"网络忙，请重试",0);
		}else if($data==1){
			//获取订单号并取消订单
			$map['order_id']=M('order_adj')->where('adj_id='.$orderId)->getField("order_id");
			$res=M('order')->where($map)->setField("status",100);
			if($res){
				log::write("取消订单".$map['order_id']."结果：".$data);
			}

			$this->ajaxReturn($res,"取消订单成功",1);
			
		}
	}




	//地址转换为经纬度
	public function geocoder(){

		$url="http://api.map.baidu.com/geocoder/v2/?ak=".C("baiduMapKey");
		$url.="&output=json";	//规定返回数据格式
		$url.="&address=".urlencode($_POST['address']);

		$data=file_get_contents($url);
		$data=json_decode($data,true);
		if($data['status']==0){
			$this->ajaxReturn($data['result'],"地址转换成功",1);
		}else{
			$this->ajaxReturn("","无法获取定位，请重试！",0);
		}
	}


	//坐标转换API，把GPS坐标转换为百度坐标
	public function geoconv(){
		$location=$_POST["lat"].",".$_POST["lon"];
		$output="html";	//表示输出类型，web上必须指定为html才能展现地图产品结果。
		$from="1";
		$key=C("baiduMapKey");
		$url="http://api.map.baidu.com/geoconv/v1/?ak=".C("baiduMapKey");
		$url.="&coords=120.2534241,30.173119099999997&output=json";

		//$url=urlencode($url);
		//{"status":0,"result":[{"x":120.26434801937,"y":30.176881129349}]}

		echo $url;
		$data=file_get_contents($url);
		$data=json_decode($data,true);

		dump($data);

	}



	//与爱代驾交互用
	public function curls($url, $data_string) {
	    $ch = curl_init();
	    curl_setopt($ch, CURLOPT_URL, $url);
	    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
	        'X-AjaxPro-Method:ShowList',
	        'Content-Type: application/json; charset=utf-8',
	        'Content-Length: ' . strlen($data_string))
	    );
	    curl_setopt($ch, CURLOPT_POST, 1);
	    curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
	    $data = curl_exec($ch);
	    curl_close($ch);
	    return $data;
	}

    
}

?>